package com.yun.datastructure.tree.heap;

public class Heap {
    private int[] array;
    private int size;
    private boolean max;

    public Heap(int capacity, boolean max) {
        this.array = new int[capacity];
        this.max = max;
    }

    public Heap(int[] nums, boolean max) {
        this.array = nums;
        this.size = nums.length;
        this.max = max;
    }

    //建堆
    public void heapify() {
        for (int i = size / 2 - 1; i > 0; i--) {
            down(i);
        }
    }

    //向堆尾部添加元素
    public void offer(int offered) {
        if (isFull()) {
            //扩容
            grow();
        }
        up(offered);
        size++;
    }

    public int poll() {
        if (isEmpty()) {
            throw new NullPointerException();
        }
        int top = array[0];
        swap(0, size - 1);
        size--;
        down(0);
        return top;
    }

    public int peek() {
        if (isEmpty()) {
            throw new NullPointerException();
        }
        return array[0];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == array.length;
    }

    private int[] getArray() {
        return array;
    }

    public int getSize() {
        return size;
    }

    //扩容
    private void grow() {
        int capacity = size + (size >> 1);
        int[] newArray = new int[capacity];
        System.arraycopy(array, 0, newArray, 0, size);
        array = newArray;
    }

    //上浮
    private void up(int offered) {
        int child = size;
        while (child > 0) {
            int parent = (child - 1) / 2;
            boolean cmp=max?array[parent]<offered : array[parent] > offered;
            if (cmp) {
                array[child] = array[parent];
            } else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }

    //下潜
    private void down(int parent) {
        int left = parent * 2 + 1;
        int right = left + 1;
        int maxOrMin = parent;
        if (left < size && (max ? array[left] > array[maxOrMin] : array[left] < array[maxOrMin])) {
            maxOrMin = left;
        }
        if (right < size && (max ? array[right] > array[maxOrMin] : array[right] < array[maxOrMin])) {
            maxOrMin = right;
        }
        if (maxOrMin != parent) {
            swap(maxOrMin, parent);
            down(maxOrMin);
        }
    }

    //交换
    private void swap(int i, int j) {
        int t = array[i];
        array[i] = array[j];
        array[j] = t;
    }

}
